import requests
import random
from PIL import Image
import io
from ddddocr import DdddOcr

slide = DdddOcr(det=False,ocr=False,show_ad=False)

session = requests.Session()
value = random.random()

res = session.get(f"https://bm.ruankao.org.cn/sign/captchaImg?{value}")
print(res.cookies) # res.cookies与session.cookies一样
# print(res.content) # 打印图片字节流

# 请求图片字节流 以字节流方式保存且每次请求都会换图
with open(f'./static/sider/three.png','wb') as f:
    f.write(res.content)

# 打开图片
img = Image.open(f'./static/sider/three.png')

# 使用pillow切割图片获取背景图
bg_img = img.crop((0, 0, 240, 150))
bg_img_bytes = io.BytesIO() # 在内存中创建一个二进制字节流对象，用于临时存储二进制数据。
bg_img.save(bg_img_bytes, format='PNG') # 保存图片到字节流
# bg_img_bytes = bg_img_bytes.getvalue() # 获取字节流
# bg_img.show() # 在pycharm展示图片

# 使用pillow切割图片获取目标图
target_img = img.crop((0, 151, 50, 300))
target_img_bytes = io.BytesIO()
target_img.save(target_img_bytes, format='PNG') # 保存图片到字节流
# target_img.show() # 在pycharm展示图片

# 使用pillow切割图片获取原始图片
origin_img = img.crop((0, 301, 240, 450))
origin_img_bytes = io.BytesIO()
origin_img.save(origin_img_bytes, format='PNG') # 保存图片到字节流
# origin_img.show() # 在pycharm展示图片




# 边缘检测
res_sider = slide.slide_match(target_img_bytes.getvalue(),bg_img_bytes.getvalue())
# print(res_sider) # {'target_x': 1, 'target_y': 15, 'target': [99, 17, 147, 67]}
print(f"边缘检测",res_sider['target'][0])
offset = res_sider['target'][0] # 偏移量用于模拟滑动验证

# 图像对比
res_contrast = slide.slide_comparison(bg_img_bytes.getvalue(),origin_img_bytes.getvalue())
print(f"图像对比", res_contrast['target'][0])


res = session.post('https://bm.ruankao.org.cn/sign/inok', data={
    "s1":"NDEyNzI2MjA0NDQ=",
    "s2":"cae888005afe7f1bdc6e1cf4c6c96f9f",
    "s3":offset,
}) # s3就是偏移量
print(res.json())





